//
//  XDownloadManager.m
//  DownloaderTest
//
//  Created by user on 2018/6/13.
//  Copyright © 2018年 Dnake. All rights reserved.
//

#import "XDownloadManager.h"

@implementation XDownloadManager

+ (instancetype)shareManager {
    
    static XDownloadManager *manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    
    return manager;
}


- (instancetype)init {
    
    if (self = [super init]) {
        
        _taskDict = [[NSMutableDictionary alloc] init];
        
        // 后台下载标识
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"HWDownloadBackgroundSessionIdentifier"];
        // 允许蜂窝网络下载，默认为YES，这里开启，我们添加了一个变量去控制用户切换选择
        configuration.allowsCellularAccess = YES;
        
        _afSessionManager = [[AFHTTPSessionManager manager] initWithSessionConfiguration:configuration];
        
    }
    return self;
}

- (void)startDownloadTask:(XDownloadModel *)model ProgressBlock:(ProgressBlock)block {
    if (model.task) {
        return;
    }
    NSURLSessionDownloadTask *task = [_afSessionManager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:model.url]] progress:^(NSProgress * _Nonnull downloadProgress) {
        
        CGFloat percent = 1.0 * downloadProgress.completedUnitCount/downloadProgress.totalUnitCount;
        model.progress = percent;
        if (block) {
            block(model.progress);
        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSURL *fileURL = [NSURL fileURLWithPath:model.filePath];
        return fileURL;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        model.filePath = filePath.path;
        
    }];
    
    [task resume];
    
    model.task = task;
    
}

- (void)pauseDownloadTask:(XDownloadModel *)model {
    
    NSURLSessionDownloadTask *task = model.task;
    [task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        model.resumeData = resumeData;
    }];
}

- (void)continueDownloadTask:(XDownloadModel *)model ProgressBlock:(ProgressBlock)block {
    
    NSURLSessionDownloadTask *task = [_afSessionManager downloadTaskWithResumeData:model.resumeData progress:^(NSProgress * _Nonnull downloadProgress) {
        CGFloat percent = 1.0 * downloadProgress.completedUnitCount/downloadProgress.totalUnitCount;
        model.progress = percent;
        if (block) {
            block(model.progress);
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSURL *fileURL = [NSURL fileURLWithPath:model.filePath];
        return fileURL;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        model.filePath = filePath.path;
    }];
    
    [task resume];
    
    model.task = task;
    
}

@end
